package homework.socket;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client {
    private Socket socket;
    private Client() {
        try {
            socket = new Socket("localHost", 9991);
            System.out.println("111111");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        try {
            ServerHandler serverHandler = new ServerHandler();
            Thread thread = new Thread(serverHandler);
            thread.start();
            OutputStream os = socket.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
            BufferedWriter bw = new BufferedWriter(osw);
            PrintWriter pw = new PrintWriter(bw,true);
            Scanner scanner = new Scanner(System.in);
            String message;
            System.out.println("请输入昵称：");
            while (true){
                message = scanner.nextLine();
                if (message.isEmpty()){
                    pw.println("昵称不能为空");
                }else {
                    pw.println(message);
                    break;
                }
            }
            while (true){
                message = scanner.nextLine();
                if ("exist".equalsIgnoreCase(message)){
                    break;
                }else {
                    pw.println(message);
                }
            }
        } catch (IOException e) {
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
    class ServerHandler implements Runnable{
        @Override
        public void run() {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine())!=null){
                    System.out.println(line);
                }
            } catch (IOException e) {
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static void main(String[] args) {
        Client client = new Client();
        client.start();
    }

}
